package desmontec.sistema

import desmontec.util.Constantes;



class SecUserController {
	
	SecUserService secUserService;
	def  springSecurityService
	def mailService
    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index = {
        redirect(action: "welcome")
    }
	//fernando.alves - inicio
    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
		def usuarios = SecUser.list()
		for(int i = 0; i < usuarios.size; i++){
			def u = usuarios.get(i)
			if (u.ehAdmin())
				usuarios.remove u
		}
		[secUserInstanceList: usuarios, secUserInstanceTotal: usuarios.size]
    }

    def create = {
        def secUserInstance = new SecUser()
        secUserInstance.properties = params
        return [secUserInstance: secUserInstance]
    }

	//fernando.alves - fim
    def save = {
        def secUserInstance = new SecUser(params)
		//fernando.alves - inicio
		secUserInstance.accountExpired = false
		secUserInstance.passwordExpired = false
		secUserInstance.enabled = true
//		secUserInstance.accountLocked = secUserService.validaConta(params.dataValidade)
		secUserInstance.accountLocked = false
		secUserInstance.dataValidade = params.dataValidadeUsuario
		if (secUserInstance.save(flush: true)) {
			secUserInstance.password = springSecurityService.encodePassword(params.password)
			new SecUserSecRole(secUser: secUserInstance, secRole: SecRole.findByAuthority(Constantes.USUARIO_COMUM)).save(flush: true, insert: true)
			//fernando.alves - fim
            flash.message = "${message(code: 'desmontec.sistema.SecUser.default.created.message', args: [message(code: 'secUser.label', default: 'SecUser'), secUserInstance.id])}"
            redirect(action: "show", id: secUserInstance.id)
        }
        else {
            render(view: "create", model: [secUserInstance: secUserInstance])
        }
    }

    def show = {
        def secUserInstance = SecUser.get(params.id)
        if (!secUserInstance) {
            flash.message = "${message(code: 'desmontec.sistema.SecUser.default.not.found.message', args: [message(code: 'secUser.label', default: 'SecUser'), params.id])}"
            redirect(action: "list")
        }
        else {
            [secUserInstance: secUserInstance]
        }
    }

    def edit = {
        def secUserInstance = SecUser.get(params.id)
        if (!secUserInstance) {
            flash.message = "${message(code: 'desmontec.sistema.SecUser.default.not.found.message', args: [message(code: 'secUser.label', default: 'SecUser'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [secUserInstance: secUserInstance, ehUsuarioAdm: springSecurityService.getCurrentUser().ehAdmin()]
        }
    }

    def update = {
        def secUserInstance = SecUser.get(params.id)
        if (secUserInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (secUserInstance.version > version) {
                    
                    secUserInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'secUser.label', default: 'SecUser')] as Object[], "Another user has updated this SecUser while you were editing")
                    render(view: "edit", model: [secUserInstance: secUserInstance], ehUsuarioAdm: springSecurityService.getCurrentUser().ehAdmin())
                    return
                }
            }
            secUserInstance.properties = params
			//fernando.alves - inicio
			
			if (params.dataValidadeUsuario != null) {
				secUserInstance.accountLocked = secUserService.validaConta(params.dataValidadeUsuario)
				secUserInstance.dataValidade = params.dataValidadeUsuario
				
			}
			//fernando.avles - fim
			if (!secUserInstance.hasErrors() && secUserInstance.save(flush: true)) {
                flash.message = "${message(code: 'desmontec.sistema.SecUser.default.updated.message', args: [message(code: 'secUser.label', default: 'SecUser'), secUserInstance.id])}"
                redirect(action: "show", id: secUserInstance.id)
            }
            else {
                render(view: "edit", model: [secUserInstance: secUserInstance], ehUsuarioAdm: springSecurityService.getCurrentUser().ehAdmin())
            }
        }
        else {
            flash.message = "${message(code: 'desmontec.sistema.SecUser.default.not.found.message', args: [message(code: 'secUser.label', default: 'SecUser'), params.id])}"
            redirect(action: "list")
        }
    }
	
	//fernando.alves - inicio
	
	def alterarDadosPessoais = {
		params.id = springSecurityService.getCurrentUser().id
		redirect(action:"edit", params:params, ehUsuarioAdm: springSecurityService.getCurrentUser().ehAdmin())
		return
	}
	def alterarSenha = {
		render(view: "alterarSenha", model: [secUserInstance: (SecUser) springSecurityService.getCurrentUser()])
	}
	
	def atualizarSenha = {
		if (params.novaSenha != params.confirmarSenha){
			flash.message = "Confirmacao da senha nao confere"
			redirect(action: "alterarSenha")
		} else if (params.novaSenha.length() < 5 || params.novaSenha.length() > 60){
			flash.message = "${message(code: 'desmontec.sistema.SecUser.password.size.toobig')}"
			redirect(action: "alterarSenha")
		} else if (springSecurityService.encodePassword(params.senhaAtual) != springSecurityService.getCurrentUser().password) {
			flash.message = "Senha nao confere"
			redirect(action: "alterarSenha")
		} else {
			SecUser usuarioAtual = (SecUser) springSecurityService.getCurrentUser()
			usuarioAtual.password = springSecurityService.encodePassword(params.novaSenha)
			flash.message = "Senha alterada com sucesso"
			redirect(action: "alterarSenha")
		}
			
	}
	
	def recuperarSenha = {
		render(view: "recuperarSenha")
	}
	
	def geraNovaSenha = {
		def usuarios = SecUser.findAllByEmail(params.email)
		
		if (usuarios.size == 0){
			//erro
			flash.message = "Nao foi possivel encontrar usuario com esse email"
		} else {
			def sucess = true
			for (u in usuarios){
				sucess = secUserService.geraNovaSenha(u)
			}
			if (sucess) {
				flash.message = "Um email foi enviado com a nova senha"
			} else {
			flash.message = "Nao foi possivel enviar o email, por favor contate o administrador"
			}
		}
		redirect(action: "recuperarSenha")
	}
	
	def welcome = {
		render(view: "welcome", model: [secUserInstance: (SecUser) springSecurityService.getCurrentUser(), ehUsuarioAdm: springSecurityService.getCurrentUser().ehAdmin()])
	}
	
	//fernando.alves - fim
    def delete = {
        def secUserInstance = SecUser.get(params.id)
        if (secUserInstance) {
            try {
				def roles = SecUserSecRole.findAllBySecUser(secUserInstance)
				for (r in roles){
					r.delete(flush:true)
				}
                secUserInstance.delete(flush: true)
                flash.message = "${message(code: 'desmontec.sistema.SecUser.default.deleted.message', args: [message(code: 'secUser.label', default: 'SecUser'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'desmontec.sistema.SecUser.default.not.deleted.message', args: [message(code: 'secUser.label', default: 'SecUser'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'desmontec.sistema.SecUser.default.not.found.message', args: [message(code: 'secUser.label', default: 'SecUser'), params.id])}"
            redirect(action: "list")
        }
    }
	
	
	
	
}
